package com.cskaoyan.service.impl;

import com.cskaoyan.bean.*;
import com.cskaoyan.bean.yangzihui.*;
import com.cskaoyan.mapper.CouponMapper;
import com.cskaoyan.mapper.MarketCouponMapper;
import com.cskaoyan.mapper.MarketCouponUserMapper;
import com.cskaoyan.mapper.MarketUserMapper;
import com.cskaoyan.service.CouponService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * @author yangzihui
 * @Description
 * @Create 2022-06-30 10:55
 * @Version
 */
@Service
@Transactional
public class CouponServiceImpl implements CouponService {

    @Autowired
    CouponMapper couponMapper;
    @Autowired
    MarketUserMapper marketUserMapper;
    @Autowired
    MarketCouponMapper marketCouponMapper;
    @Autowired
    MarketCouponUserMapper marketCouponUserMapper;

    // 生成优惠券兑换码
    private String generateShortUuid() {
        String[] chars = new String[]{"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p",
                "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A",
                "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V",
                "W", "X", "Y", "Z"};
        StringBuffer shortBuffer = new StringBuffer();
        String uuid = UUID.randomUUID().toString().replace("-", "");
        for (int i = 0; i < 8; i++) {
            String str = uuid.substring(i * 4, i * 4 + 4);
            int x = Integer.parseInt(str, 16);
            shortBuffer.append(chars[x % 0x3E]);
        }
        return shortBuffer.toString();

    }

    @Override
    public CouponListPo list(Integer page, Integer limit, Integer id) {
        Date date = new Date();
        List<Date> date1 = couponMapper.getEndTime(id);
        for (Date date2 : date1) {
            if (date2.compareTo(date) < 0) {
                couponMapper.setStatus(id, date2);
            }
        }
        PageHelper.startPage(page, limit);
        List<CouponList> couponListList = couponMapper.list();
        PageInfo pageInfo = new PageInfo(couponListList);
        long total = pageInfo.getTotal();
        int pages = pageInfo.getPages();
        return CouponListPo.data(total, pages, limit, page, couponListList);
    }

    @Override
    public CouponMyListPo myList(Integer id, Integer status, Integer page, Integer limit) {
        PageHelper.startPage(page, limit);
        List<CouponMyList> couponMyListList = couponMapper.myList(id, status);
        Date date = new Date();
        List<Date> date1 = couponMapper.getEndTime(id);
        for (Date date2 : date1) {
            if (date2.compareTo(date) < 0) {
                couponMapper.setStatus(id, date2);
            }
        }
        PageInfo pageInfo = new PageInfo(couponMyListList);
        long total = pageInfo.getTotal();
        int pages = pageInfo.getPages();
        return CouponMyListPo.data(total, pages, limit, page, couponMyListList);
    }

    @Override
    public Integer receive(Integer id, Integer couponId) {
        try {
            Date date = new Date();
            Integer total = couponMapper.queryTotal(couponId);
            if (total != null && total == -1) {
                return total;
            }
            Integer couponNum = couponMapper.hasCoupon(id, couponId);
            if (couponNum == 0) {
                FinalCouponVo finalCouponVo = couponMapper.queryCoupon(couponId);
                if (finalCouponVo.getTimeType() == 0) {
                    Calendar cr = Calendar.getInstance();
                    cr.setTime(date);
                    cr.add(Calendar.DAY_OF_YEAR, finalCouponVo.getDays());
                    Date time = cr.getTime();
                    couponMapper.insertCoupon(id, couponId, finalCouponVo, date, time);
                } else if (finalCouponVo.getTimeType() == 1) {
                    couponMapper.insertCouponByStartTime(id, couponId, finalCouponVo, date);
                }
                if (total != null && total == 0) {
                    return 2;
                }
                if (total != null && total == 1) {
                    Integer counts = finalCouponVo.getTotal() - 2;
                    couponMapper.updateCoupon(couponId, counts);
                    return 2;
                }
                Integer counts = finalCouponVo.getTotal() - 1;
                couponMapper.updateCoupon(couponId, counts);
                return 2;
            } else {
                Integer limit = couponMapper.selectLimit(couponId);
                Integer count = couponMapper.selectCount(id, couponId);
                if (limit == 1) {
                    return limit;
                } else if (count == limit) {
                    return 1;
                } else if (count < limit) {
                    FinalCouponVo finalCouponVo = couponMapper.queryCoupon(couponId);
                    if (finalCouponVo.getTimeType() == 0) {
                        Calendar cr = Calendar.getInstance();
                        cr.setTime(date);
                        cr.add(Calendar.DAY_OF_YEAR, finalCouponVo.getDays());
                        Date time = cr.getTime();
                        couponMapper.insertCoupon(id, couponId, finalCouponVo, date, time);
                    } else if (finalCouponVo.getTimeType() == 1) {
                        couponMapper.insertCouponByStartTime(id, couponId, finalCouponVo, date);
                    }
                    if (total != null && total == 0) {
                        return 2;
                    }
                    if (total != null && total == 1) {
                        Integer counts = finalCouponVo.getTotal() - 2;
                        couponMapper.updateCoupon(couponId, counts);
                        return 2;
                    }
                    Integer counts = finalCouponVo.getTotal() - 1;
                    couponMapper.updateCoupon(couponId, counts);
                    return 2;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 500;
    }


    @Override
    public Integer exchange(Integer id, String code) {
        Date date = new Date();
        Integer count = couponMapper.selectCode(code);
        Integer status = couponMapper.selectStatus(code);
        if (count != null && count == 1 && status != null && status == 0) {
            FinalCouponVo finalCouponVo = couponMapper.queryCouponByCode(code);
            Integer limit = finalCouponVo.getLimit();
            Integer total = finalCouponVo.getTotal();
            Integer couponId = finalCouponVo.getId();
            Integer num = couponMapper.selectCount(id, couponId);
            if (num == limit) {
                return 1;
            }
            if (total != null && total == 0) {
                if (finalCouponVo.getTimeType() == 0) {
                    Calendar cr = Calendar.getInstance();
                    cr.setTime(date);
                    cr.add(Calendar.DAY_OF_YEAR, finalCouponVo.getDays());
                    Date time = cr.getTime();
                    couponMapper.insertCoupon(id, couponId, finalCouponVo, date, time);
                } else if (finalCouponVo.getTimeType() == 1) {
                    couponMapper.insertCouponByStartTime(id, couponId, finalCouponVo, date);
                }
                String str = generateShortUuid();
                couponMapper.updateCode(couponId, str);
            }
            if (total != null && total > 1) {
                if (finalCouponVo.getTimeType() == 0) {
                    Calendar cr = Calendar.getInstance();
                    cr.setTime(date);
                    cr.add(Calendar.DAY_OF_YEAR, finalCouponVo.getDays());
                    Date time = cr.getTime();
                    couponMapper.insertCoupon(id, couponId, finalCouponVo, date, time);
                } else if (finalCouponVo.getTimeType() == 1) {
                    couponMapper.insertCouponByStartTime(id, couponId, finalCouponVo, date);
                }
                Integer counts = total - 1;
                couponMapper.updateCoupon(couponId, counts);
                String str = generateShortUuid();
                couponMapper.updateCode(couponId, str);
            }
            if (total != null && total == 1) {
                if (finalCouponVo.getTimeType() == 0) {
                    Calendar cr = Calendar.getInstance();
                    cr.setTime(date);
                    cr.add(Calendar.DAY_OF_YEAR, finalCouponVo.getDays());
                    Date time = cr.getTime();
                    couponMapper.insertCoupon(id, couponId, finalCouponVo, date, time);
                } else if (finalCouponVo.getTimeType() == 1) {
                    couponMapper.insertCouponByStartTime(id, couponId, finalCouponVo, date);
                }
                Integer counts = total - 2;
                couponMapper.updateCoupon(couponId, counts);
                couponMapper.updateCodeNull(couponId);
            }
            return 2;
        }
        return 742;
    }

    @Override
    public CouponMyListPo selectlist(Integer id, Integer cartId, Integer grouponRulesId) {
        Integer status = 0;
        Integer page = 1;
        Date date = new Date();
        List<Date> date1 = couponMapper.getEndTime(id);
        for (Date date2 : date1) {
            if (date2.compareTo(date) < 0) {
                couponMapper.setStatus(id, date2);
            }
        }
        Integer limit = couponMapper.count(id);
        PageHelper.startPage(page, limit);
        List<Money> moneyList = couponMapper.getTotalPrice(id);
        Double totalMoney = 0.0;
        for (Money money : moneyList) {
            totalMoney = totalMoney + money.getPrice() * money.getNumber();
        }
        List<StatusOfUser> statuses = couponMapper.getStatus(id);
        List<CouponMyList> couponMyListList = couponMapper.getAllCoupon(id);
        for (CouponMyList couponMyList : couponMyListList) {
            if (couponMyList.getMin() <= totalMoney) {
                for (StatusOfUser statusOfUser : statuses) {
                    if (statusOfUser.getId() == couponMyList.getId()) {
                        couponMyList.setAvailable(true);
                    }
                }
                continue;
            }
            couponMyList.setAvailable(false);
        }
        PageInfo pageInfo = new PageInfo(couponMyListList);
        long total = pageInfo.getTotal();
        int pages = pageInfo.getPages();
        return CouponMyListPo.data(total, pages, limit, page, couponMyListList);
    }


    @Override
    public void addCouponToNewUser(String username) {
        MarketUserExample marketUserExample = new MarketUserExample();
        MarketUserExample.Criteria criteria = marketUserExample.createCriteria();
        criteria.andUsernameEqualTo(username);
        List<MarketUser> marketUsers = marketUserMapper.selectByExample(marketUserExample);
        MarketCouponExample couponExample = new MarketCouponExample();
        MarketCouponExample.Criteria couponExampleCriteria = couponExample.createCriteria();
        couponExampleCriteria.andTypeEqualTo((short)1);
        List<MarketCoupon> coupons = marketCouponMapper.selectByExample(couponExample);
        for (MarketCoupon coupon : coupons) {
            for (MarketUser marketUser : marketUsers) {
                MarketCouponUser couponUser = new MarketCouponUser();
                couponUser.setCouponId(coupon.getId());
                couponUser.setUserId(marketUser.getId());
                couponUser.setAddTime(new Date());
                couponUser.setStartTime(new Date());
                Date date = DateUtils.addDays(new Date(), coupon.getDays());
                couponUser.setEndTime(date);
                marketCouponUserMapper.insertSelective(couponUser);

            }
        }
    }
}
